<template>
  <el-row class="aa">
    <el-col :span="18" class="bb">
      <p>查询条件</p>
      <!-- 左半部=================-==================分 -->
      <el-row class="condition_box" type="flex" justify="space-between">
        <el-form
          :inline="true"
          :model="formInline"
          ref="formInline"
          class="demo-form-inline"
          id="fm"
        >
          <!-- 第一个col -->
          <el-col :span="8">
            <el-row class="c_radio">
              <el-radio @change="c_radio" v-model="radio" :label="1">单站查询</el-radio>
              <!-- <el-radio :label="'多站查询'">多站查询</el-radio> -->
              <!-- <el-radio v-model="radio" label="1">单站查询</el-radio>
              <el-radio v-model="radio" label="2">多站查询</el-radio>-->
            </el-row>
            <el-row>
              <el-form-item label="要素选择：">
                <el-select @change="sele_change" v-model="value1" multiple placeholder="请选择子站后进行操作">
                  <el-option
                    v-for="item in options"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-row>
          </el-col>
          <!-- 第二个col -->
          <el-col :span="8">
            <el-row>
              <el-col>
                <el-form-item label="选择站点:" prop="station_id">
                  <el-select
                    @change="c_select"
                    size="mini"
                    v-model="formInline.station_id"
                    placeholder="请选择"
                  >
                    <el-option
                      :key="item.station.id"
                      v-for="item in station"
                      :label="item.station.name"
                      :value="item.station.id"
                    ></el-option>
                    <!-- <el-option label="站点二" value="beijing"></el-option> -->
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col>
                <div class="block">
                  <span class="demonstration">查询时间:</span>
                  <el-date-picker
                    @change="date_change"
                    v-model="value2"
                    value-format="yyyy-MM-dd HH:mm:ss"
                    type="datetimerange"
                    :picker-options="pickerOptions"
                    range-separator="至"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期"
                    align="right"
                  ></el-date-picker>
                </div>
              </el-col>
            </el-row>
          </el-col>
          <!-- 第三个col -->
          <el-col :span="8">
            <el-row class="selector_station">
              <el-form-item label="选择子站：" prop="kid_station">
                <el-select
                  @change="kid_station_name"
                  size="mini"
                  v-model="formInline.kid_station"
                  placeholder="请选择站点后在进行操作"
                >
                  <el-option
                    :key="k"
                    v-for="(item,k) in kid_station"
                    :label="item.name"
                    :value="item.serial"
                  ></el-option>
                  <!-- <el-option label="站点二" value="beijing"></el-option> -->
                </el-select>
              </el-form-item>
            </el-row>
          </el-col>
        </el-form>
      </el-row>
      <!-- 按钮盒子 -->
      <el-row class="btn_box" type="flex" justify="end">
        <el-button type="primary" @click="datas_by_range">查询</el-button>
        <el-button type="danger" @click="clear_all">重置</el-button>
        <el-button type="success" @click="exportExcel">导出</el-button>
      </el-row>
      <el-card class="table_card">
        <!-- 表格数据展示 -->
        <el-table border id="el_table" :data="tableData[1]" style="width: 100%">
          <!-- <el-table-column :key="k" v-for="(item,k) in tableData" prop label="序号" width="41"></el-table-column> -->
          <!--  <el-table-column prop="date" label="站点ID" width="67"></el-table-column> -->
          <!-- <el-table-column prop="date" label="站点名称" width="80"></el-table-column> -->
          <el-table-column prop="update_time" label="更新时间" width="180"></el-table-column>
          <el-table-column
            :key="k"
            v-for="(item,k) in tableData[0]"
            :prop="item.elementSort"
            :label="item.elementName+''+'('+item.elementUnit+')'"
          ></el-table-column>
        </el-table>
      </el-card>

      <!-- 分页功能=========== -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="page"
        :page-sizes="[1, 3, 5, 8]"
        :page-size="5"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </el-col>
    <!-- 右半部分================================================ -->
    <el-col :span="6" class="bb">
      <el-card class="box-card">
        <div slot="header" class="clearfix">
          <span>要素日统计</span>
        </div>
        <div class="Statistics">
          <el-tabs v-model="activeName" @tab-click="handleClick">
            <el-tab-pane
              :key="k"
              v-for="(item,k) in options"
              :label="item.label"
              :name="item.value"
            >
              <el-form
                class="day_form"
                label-position="left"
                label-width="80px"
                :model="formLabelAlign"
              >
                <el-form-item prop label="最大值">
                  <el-input readonly v-model="day_data.data.max"></el-input>
                </el-form-item>
                <el-form-item class="max_min" prop label="最大值出现时间">
                  <el-input readonly v-model="day_data.data.timeOfMax"></el-input>
                </el-form-item>
                <el-form-item prop label="最小值">
                  <el-input readonly v-model="day_data.data.min"></el-input>
                </el-form-item>
                <el-form-item class="max_min" prop label="最小值出现时间">
                  <el-input readonly v-model="day_data.data.timeOfMin"></el-input>
                </el-form-item>
              </el-form>
            </el-tab-pane>
          </el-tabs>
        </div>
      </el-card>
      <!-- 统计数据 -->
      <el-card class="data_statistics box-card">
        <div slot="header" class="clearfix">
          <span>统计</span>
        </div>
        <div class="date_box">
          <p>请选择开始与结束时间</p>
          <el-date-picker
            v-model="value3"
            type="datetimerange"
            :picker-options="pickerOptions"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            align="right"
            @change="statistics"
          ></el-date-picker>
        </div>
        <div ref="input_boxs" class="input_boxs">
          <el-form label-position="left" label-width="80px" :model="formInline">
            <div :key="k" v-for="(item,k) in statistics_m_n">
              <el-form-item :label="item.driveElementSingle.elementName+''+'(最大值)'">
                <el-input readonly v-model="item.data.max"></el-input>
              </el-form-item>
              <el-form-item :label="item.driveElementSingle.elementName+'(最小值)'">
                <el-input readonly v-model="item.data.min"></el-input>
              </el-form-item>
            </div>
          </el-form>
        </div>
      </el-card>
    </el-col>
  </el-row>
</template>

<script>
// 仅限在组件里边导入
import FileSaver from "file-saver";
import XLSX from "xlsx";

import Qs from "qs";
import dateFtt from "../assets/lib/time.js";

export default {
  created() {
    this.one_data();
  },
  mounted() {
    this.p_1366();
    var a = new Date().toLocaleDateString();
    var b = new Date().toLocaleDateString();
    a = a.split("/").join("-") + " 00:00:00";

    b = b.split("/").join("-") + " 23:59:00";
    this.value2[0] = a;
    this.value2[1] = b;
    this.value2 = [...this.value2];
  },
  data() {
    return {
      // 页数
      page: 1,
      // 一页有几条数据
      pageSize: 5,
      // 总页数
      total: 0,
      // 用户信息
      user_info: this.$store.state.user_info.data,
      // 站点列表信息
      station: [],
      // 子站（气象站）信息
      kid_station: [],
      // 元素选择列表(data1,data2...)
      value1: [],
      // 元素数据
      // 元素展示列表
      options: [],
      // datas
      el_datas: [],
      checked: true,
      radio: 1,
      t_radio: true,
      formInline: {
        // 默认站点
        station_id: "",
        // 默认子站
        kid_station: "",
        // 气象站点名字
        station_k_name: "",
        // 气象站点id
        station_k_id: 3
      },
      pickerOptions: {},
      // 时间选择器的默认存储时间的地方
      value2: ["2019-03-25 00:00:00", "2019-03-26 00:00:00"],
      // 选中卡片的name值
      activeName: "data1",
      // 气压表单
      formLabelAlign: {},
      value3: ["2019-01-11 00:00:00", "2019-11-11 00:00:00"],
      // 表格数据存放
      tableData: [],
      // 保存当前子站点的HCD719032301
      // station_serial: "",
      // 气象站选择时筛选出来的对象
      k_station_filter: [],
      // 要素日统计数据存放（一定设置一个默认追，因为是v-model）
      day_data: {
        data: {
          max: "今日暂无",
          timeOfMax: "今日暂无",
          min: "今日暂无",
          timeOfMin: "今日暂无"
        }
      },
      // 元素封装操作
      obj_data: {},
      // 子站序好
      kid_serial: "",
      // 某一时间段内的最大值和最小值
      statistics_m_n: []
    };
  },
  methods: {
    // 1366
    p_1366() {
      if (window.screen.width <= 1366) {
        this.$refs.input_boxs.style = "padding-bottom:80px";
      }
      console.log(window.screen.width);
    },
    // 统计部分
    async statistics(serial) {
      var { data: res } = await this.$http.post(
        "/data/getExtremumDatasByRange",
        Qs.stringify({
          serial: serial,
          startTime: this.value3[0],
          endTime: this.value3[1]
        })
      );
      if (res.status != 0) return this.$notify.warning("暂无时间段内最大数据");
      this.statistics_m_n = res.datas;
      console.log(res);
    },
    // tab栏切换事件，改变activename

    // 要素日统计的ajax发送(要根据该气象站，本身所拥有的元素查询)
    async daily_statistics(serial, data1) {
      // 接口所需要的序列号和元素字段名
      var obj = {
        serial: serial,
        elementSort: data1
      };
      // 发送数据后台需要json格式 qs转一下
      let { data: res } = await this.$http.post(
        "/data/getExtremumDatas",
        Qs.stringify(obj)
      );
      // 找到与返回数据的元素匹配(为了提示信息)
      var abj = this.options.filter(item => {
        return data1 == item.value;
      });
      // 没有数据就返回提示信息
      if (res.status == 7) {
        return this.$notify.info(abj[0].label + "暂无当天数据");
      }
      // 返回的数据放在data
      this.day_data = res;

      this.day_data.data.max += abj[0].unit;
      this.day_data.data.min += abj[0].unit;
      // 获取当前气象站下所有元素的某一段时间下的最大最小值
      // /data/getExtremumDatasByRange
    },

    // 导出Excel表格操作
    exportExcel() {
      /* generate workbook object from table */
      let wb = XLSX.utils.table_to_book(document.querySelector("#el_table"));
      /* get binary string as output */
      let wbout = XLSX.write(wb, {
        bookType: "xlsx",
        bookSST: true,
        type: "array"
      });
      try {
        FileSaver.saveAs(
          new Blob([wbout], { type: "application/octet-stream" }),
          "表格数据.xlsx"
        );
      } catch (e) {
        if (typeof console !== "undefined") console.log(e, wbout);
      }
      this.$message.success("导出操作完成");
      return wbout;
    },
    // 点击下一页事件
    handleSizeChange(val) {
      this.pageSize = val;

      this.datas_by_range();
    },
    // 点击一页显示一条数据事件
    handleCurrentChange(val) {
      this.page = val;

      this.datas_by_range();
    },
    // 当选择站点的下拉框变动时
    async fn1(id) {
      // 每次调用之前要先把上一次的value值清除(不然会叠加)
      this.value1 = [];

      var k_obj = this.station.filter(item => {
        // if (item.id == id)
        return item.station.id == id;
      });
      this.kid_station = k_obj[0].collectorSingles;
      this.formInline.kid_station = k_obj[0].collectorSingles.serial;
    },
    // 找某个气象站下可以查看的元素的操作封装
    find_element(res) {
      if (res.status == 7) return this.$message.error(res.msg);
      // 每次调用之前要先把上一次的value值清除(不然会叠加)
      this.value1 = [];
      res.labels.forEach((item, index) => {
        this.obj_data = {
          value: res.labels[index].elementSort,
          label: res.labels[index].elementName,
          unit: res.labels[index].elementUnit
        };
        if (!this.$route.params.id) {
          // this.value1.push(this.obj_data.value);
        }
        this.options.push(this.obj_data);
      });
    },

    // 根据传过来的值加载首屏数据
    async one_data() {
      let serial = this.$route.params.id;
      // 将默认值子站填入表单指定区域
      this.formInline.kid_station = serial;
      this.kid_serial = serial;

      if (!serial) {
        // 单点数据查询 假设没有通过按钮跳转
        let { data: res2 } = await this.$http(
          `/station/listStationsAndCollectorSingle/${this.user_info.id}`
        );
        this.station = res2.datas;

        // this.daily_statistics(serial, "data1");

        return false;
      }

      // 获取数据请求==============================================================用户点击按钮时的代码
      const { data: res } = await this.$http(`/data/realtimeSingle/${serial}`);

      if (res.status == 5) return this.$message.error(res.msg);

      this.options = [];
      // 找元素======函数这里是先找到按钮跳转过来的时候 的帮忙选好的默认元素
      this.find_element(res);

      // 获取站点请求==================================================================
      const { data: res1 } = await this.$http(
        `/station/listStationsAndCollectorSingle/${this.user_info.id}`
      );
      // 当日的元素统计
      this.daily_statistics(serial, "data1");
      this.statistics(serial);
      this.station = res1.datas;
      // 筛选出对应的子站
      this.station.forEach(item => {
        item.collectorSingles.forEach(item2 => {
          // 根据对比 找到 用户点击 跳转的时候 选择的是哪个气象站
          // 跳转的时候 携带的serial(this.kid_serial)
          // 数据返回的所有serial(item2.serial) 循环时进行判断
          if (item2.serial == this.kid_serial) {
            this.formInline.station_id = item.station.id;
            this.formInline.station_name = item2.name;
            // 放在判断里边的话会找到 当前站点下的 气象站
            // 放在外边的就是所有的气象站
            this.kid_station.push(item2);
          }
        });
      });
      // console.log(this.formInline.station_name);
    },
    // 点击重置按钮
    clear_all() {
      // 拿到所有数据清空
      // 站点信息清空
      // this.station = [];
      // 元素选择列表清空
      this.value1 = [];
      // 清空时间数组
      this.value2 = [];
      // 清空表单元素 含 站点和 子站点
      this.$refs.formInline.resetFields();
      // 由于赋值之后的表单元素无法进行重置清除，所有重新赋值字符串
      this.formInline.kid_station = "";
      this.$message("表单已重置");
    },
    // 点击气象站查询数据(查询按钮事件)
    async datas_by_range() {
      var dateFtt1 = dateFtt.dateFtt;

      // 提醒用户选择站点和子站
      if (!this.formInline.station_id) {
        return this.$message.warning("请选择站点");
      } else if (!this.formInline.kid_station) {
        return this.$message.warning("请选择子站");
      }
      this.tableData = [];
      // 将对象打包好发送出去，记得使用qs转格式
      var abc = {
        // 气象站序列号
        serial: this.formInline.kid_station,
        // 要查询的元素的字段
        gogals: this.value1.join(","),
        // 开始时间
        startTime: this.value2[0],
        // 结束时间
        endTime: this.value2[1],
        // 查询几页
        page: this.page,
        // 一页有几条数据
        pageSize: this.pageSize
      };

      var { data: res } = await this.$http.post(
        "/data/listSingleDatasByRange",
        Qs.stringify(abc)
      );
      if (res.status != 0) return this.$message.warning(res.msg);
      console.log(res);
      this.total = res.total;
      this.tableData.push(res.labels);
      this.tableData.push(res.datas);
    },
    // 选择气象站事件
    async kid_station_name(serial) {
      console.log(serial);

      // 过滤出来对应的子站名（找气象站名的操作）
      var data = this.kid_station.filter(item => {
        return item.serial == serial;
      });
      this.formInline.station_k_name = data[0].name;
      // 找该气象站下的可以查询的元素
      let { data: res } = await this.$http(`/data/realtimeSingle/${serial}`);

      if (res.status == 5) return this.$message.error(res.msg);
      // 在push之前尽量清空原数组以免发生叠加的状况
      this.options = [];
      // 这是用户没有点击按钮查数据时的查询操作，需要在选择完气象站之后 进行的操作
      this.find_element(res);
      // 用户选择完气象站之后 将当日的元素信息展现出来
      this.daily_statistics(serial, "data1");
      // 默认统计一段时间的最大最小值
      this.statistics(serial);
    },
    // 选择站点的操作
    c_select(a) {
      this.fn1(a);
      // console.log(a);
    },
    sele_change(a) {
      console.log(a);

      // console.log(this.value1);
    },
    c_radio(a) {
      console.log(a);
    },
    date_change(a) {
      // console.log(new Date(a[1]).toLocaleString());
      // console.log(a);
      console.log(this.value2);
    },
    time_radio(a) {
      console.log(a);
    },
    // tab切换事件
    handleClick(a) {
      this.daily_statistics(this.formInline.kid_station, a.name);
      // this.formInline.kid_station
      console.log(a.name);
    }
  }
};
</script>

<style lang="less" scoped>
// 适配1366
#fm {
  .el-form-item,
  .block {
    display: flex;
    .el-form-item__label,
    .demonstration {
      line-height: 30px;
      text-align: left !important;
      white-space: nowrap !important ;
    }
  }
}

.input_boxs .el-input {
  margin-left: 28px;
}

.el-table,
.table_card {
  margin-top: 20px;
}
// 统计数据盒子input框展示
.input_boxs {
  overflow: auto;
  // height: 280px;
  max-height: 360px;
  // padding-bottom: 60px;
}
// 时间盒子
.date_box {
  border-bottom: 2px dashed #c7c8ca;
  padding-bottom: 10px;
}
.data_statistics,
.el-card__body {
  padding-bottom: 30px;

  height: 55%;
  .el-card__body {
    height: 72%;
    .input_boxs {
      height: 80%;
    }
  }
  p {
    margin-bottom: 10px;
  }
}
.btn_box {
  border-bottom: 2px dashed #c7c8ca;
  padding-bottom: 20px;
}

.aa {
  height: 100%;
  .bb {
    overflow-x: hidden;
    height: 100%;

    .el-form {
      .el-col {
        height: 50px;
      }
    }
  }
}
.bb > p {
  font-size: 18px;
  color: #2c8fe0;
  background-color: #fff;
  padding: 12px 0px;
  border-bottom: 3px solid #2c8fe0;
  font-weight: 600;
}
</style>